package com.ruibang.glass.equipment.service.impl.device;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.equipment.constant.Constants;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.dto.SelectDTO;
import com.ruibang.glass.equipment.entity.device.PointCheckPlan;
import com.ruibang.glass.equipment.entity.device.PointCheckRw;
import com.ruibang.glass.equipment.entity.device.PointCheckStandardManagement;
import com.ruibang.glass.equipment.mapper.device.PointCheckPlanMapper;
import com.ruibang.glass.equipment.service.PointCheckPlanService;
import com.ruibang.glass.equipment.service.PointCheckRwService;
import com.ruibang.glass.equipment.service.PointCheckStandardManagementService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 点检计划列表服务类
 * </p>
 *
 * @author mameng
 * @since 2024-03-20
 */
@Slf4j
@Service
public class PointCheckPlanServiceImpl extends ServiceImpl<PointCheckPlanMapper, PointCheckPlan> implements PointCheckPlanService {
    @Autowired
    private PointCheckStandardManagementService pointCheckStandardManagementService;

    @Autowired
    private PointCheckRwService pointCheckRwService;

    /**
     * 点检计划列表
     * @param deviceAllPageReq
     * @return
     */
    @Override
    public IPage<PointCheckPlan> getCheckPlanList(DeviceAllPageReq deviceAllPageReq) {
        IPage<PointCheckPlan> page = baseMapper.getCheckPlanList(new Page<>(deviceAllPageReq.getPageNo(), deviceAllPageReq.getPageSize()), deviceAllPageReq);
        return page;
    }

    /**
     * 新增修改
     * @param point
     * @return
     */

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public ResultBody addOrUpdateCheck(PointCheckPlan point) {
        if (StringUtils.isBlank(point.getId())) {
            baseMapper.insert(point);
            return ResultBody.success();
        }
        baseMapper.updateById(point);
        return ResultBody.success();
    }

    /**
     * 设备下拉
     * @return
     */
    @Override
    public ResultBody getListDeviceName() {
        List<PointCheckStandardManagement> list = pointCheckStandardManagementService.list();
        List<SelectDTO> selectDTOS = new ArrayList<>();
        for (PointCheckStandardManagement pointCheckStandardManagement : list) {
            SelectDTO selectDTO = new SelectDTO();
            selectDTO.setLabel(pointCheckStandardManagement.getPartId());
            selectDTO.setValue(pointCheckStandardManagement.getId());
            selectDTOS.add(selectDTO);
        }
        return ResultBody.success(selectDTOS);
    }

    @Override
    public ResultBody getUserInfo() {
        return ResultBody.success(baseMapper.getUserInfoList());
    }

    /**
     * 点检计划定时按天
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkByDayPoint() {
        List<PointCheckPlan> pointCheckPlans = baseMapper.selectList(Wrappers.<PointCheckPlan>lambdaQuery().eq(PointCheckPlan::getCycleDw, Constants.POINT_DAY).isNotNull(PointCheckPlan::getStartTime));
        if (CollectionUtils.isEmpty(pointCheckPlans)){
            return;
        }
        for (PointCheckPlan pointCheckPlan : pointCheckPlans) {
            PointCheckRw one = pointCheckRwService.getOne(Wrappers.<PointCheckRw>lambdaQuery().eq(PointCheckRw::getPlanId, pointCheckPlan.getId())
                    .orderByDesc(PointCheckRw::getStartTime).last("limit 1"));
            if (one == null) {
                //获取明天的日期
                Date startTime = pointCheckPlan.getStartTime();
                Date date = new Date();
                if (startTime.before(date)) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            } else {
                Date date = getDate(one.getStartTime(), 1);
                Date date1 = getDateNow(new Date());
                if (date1.compareTo(date) == 0) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId("");
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            }
        }
    }
    /**
     * 点检计划定时按周
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkByWeekPoint() {
        List<PointCheckPlan> pointCheckPlans = baseMapper.selectList(Wrappers.<PointCheckPlan>lambdaQuery().eq(PointCheckPlan::getCycleDw, Constants.POINT_WEEK).isNotNull(PointCheckPlan::getStartTime));
        if (CollectionUtils.isEmpty(pointCheckPlans)){
            return;
        }
        for (PointCheckPlan pointCheckPlan : pointCheckPlans) {
            PointCheckRw one = pointCheckRwService.getOne(Wrappers.<PointCheckRw>lambdaQuery().eq(PointCheckRw::getPlanId, pointCheckPlan.getId())
                    .orderByDesc(PointCheckRw::getStartTime).last("limit 1"));
            if (one == null) {
                //获取明天的日期
                Date startTime = pointCheckPlan.getStartTime();
                Date date = new Date();
                if (startTime.before(date)) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            } else {
                Date date = getDate(one.getStartTime(), 7);
                Date date1 = getDateNow(new Date());
                if (date1.compareTo(date) == 0) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            }
        }
    }
    /**
     * 点检计划定时按月
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkByMonthPoint() {
        List<PointCheckPlan> pointCheckPlans = baseMapper.selectList(Wrappers.<PointCheckPlan>lambdaQuery().eq(PointCheckPlan::getCycleDw, Constants.POINT_MONTH).isNotNull(PointCheckPlan::getStartTime));
        if (CollectionUtils.isEmpty(pointCheckPlans)){
            return;
        }
        for (PointCheckPlan pointCheckPlan : pointCheckPlans) {
            PointCheckRw one = pointCheckRwService.getOne(Wrappers.<PointCheckRw>lambdaQuery().eq(PointCheckRw::getPlanId, pointCheckPlan.getId())
                    .orderByDesc(PointCheckRw::getStartTime).last("limit 1"));
            Date newDateById = one.getStartTime();
            if (one == null) {
                //获取明天的日期
                Date startTime = pointCheckPlan.getStartTime();
                Date date = new Date();
                if (startTime.before(date)) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            } else {
                Date date = getDate(newDateById, 30);
                Date date1 = getDateNow(new Date());
                if (date1.compareTo(date) == 0) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            }
        }
    }
    /**
     * 点检计划定时按年
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkByYearPoint() {
        List<PointCheckPlan> pointCheckPlans = baseMapper.selectList(Wrappers.<PointCheckPlan>lambdaQuery().eq(PointCheckPlan::getCycleDw, Constants.POINT_YEAR).isNotNull(PointCheckPlan::getStartTime));
        if (CollectionUtils.isEmpty(pointCheckPlans)){
            return;
        }
        for (PointCheckPlan pointCheckPlan : pointCheckPlans) {
            PointCheckRw one = pointCheckRwService.getOne(Wrappers.<PointCheckRw>lambdaQuery().eq(PointCheckRw::getPlanId, pointCheckPlan.getId())
                    .orderByDesc(PointCheckRw::getStartTime).last("limit 1"));
            Date newDateById = one.getStartTime();
            if (one == null) {
                //获取明天的日期
                Date startTime = pointCheckPlan.getStartTime();
                Date date = new Date();
                if (startTime.before(date)) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            } else {
                Date date = getDate(newDateById, 365);
                String format = DateUtil.format(date, "yyyy-MM-dd");
                Date date1 = getDateNow(new Date());
                String format1 = DateUtil.format(date1, "yyyy-MM-dd");
                if (format.equals(format1)) {
                    PointCheckRw pointCheckRecord = new PointCheckRw();
                    BeanUtils.copyProperties(pointCheckPlan, pointCheckRecord);
                    pointCheckRecord.setId(null);
                    pointCheckRecord.setPlanId(pointCheckPlan.getId());
                    pointCheckRecord.setCreateTime(LocalDateTime.now());
                    pointCheckRecord.setStartTime(date);
                    pointCheckRwService.save(pointCheckRecord);
                }
            }
        }
    }


    public Date getDate(Date date, Integer day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 将日期增加一天，以获取明天的日期
        calendar.add(Calendar.DAY_OF_MONTH, day);

        // 清除时间部分，只保留日期
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 创建一个只包含日期部分的Date对象
        Date tomorrow = calendar.getTime();
        return tomorrow;
    }


    public Date getDateNow(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 清除时间部分，只保留日期
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 创建一个只包含日期部分的Date对象

        return calendar.getTime();
    }

}
